package com.hongfeng.web.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.hongfeng.web.commons.Constants;
import com.hongfeng.web.commons.Page;
import com.hongfeng.web.dao.ProductDao;
import com.hongfeng.web.item.QueryItem;
import com.hongfeng.web.item.tag.FieldOperator;
import com.hongfeng.web.item.tag.OrderOperator;
import com.hongfeng.web.model.Product;
import com.hongfeng.web.service.ProductService;

@Service
public class ProductServiceImpl implements ProductService {

	@Resource
	private ProductDao productDao;

	public List<Product> findAll() {
		return productDao.findAll();
	}

	public List<Product> findProductByTypeId(Long autoTypeId) {
		QueryItem item = new QueryItem(Product.class);
		if (autoTypeId != null) {
			item.addCondition("autoType.id", FieldOperator.EQUAL,
					autoTypeId.longValue());
		}
		List<Product> products = productDao.findAll(item);
		return products;
	}

	public List<Product> findProductByName(String name) {
		QueryItem item = new QueryItem(Product.class);
		if (name != null) {
			item.addCondition("name", FieldOperator.LIKE, name);
		}
		List<Product> products = productDao.findAll(item);
		return products;
	}

	public Page<Product> findPage(Integer pageIndex) {
		Page<Product> page = createPage(pageIndex);
		QueryItem item = new QueryItem(Product.class);
		item.addOrder("autoType.name", OrderOperator.ASC);
		return productDao.findPage(item, page);
	}

	public Page<Product> findPageByTypeId(Integer pageIndex, Long autoTypeId) {
		QueryItem item = new QueryItem(Product.class);
		item.addCondition("autoType.id", FieldOperator.EQUAL,
				autoTypeId.longValue());
		item.addOrder("autoType.name", OrderOperator.ASC);
		return productDao.findPage(item, createPage(pageIndex));
	}

	public Page<Product> findPageByBrandId(Integer pageIndex, Long autoBrandId) {
		QueryItem item = new QueryItem(Product.class);
		item.addCondition("autoType.autoBrand.id", FieldOperator.EQUAL,
				autoBrandId.longValue());
		item.addOrder("autoType.name", OrderOperator.ASC);
		return productDao.findPage(item, createPage(pageIndex));
	}

	private Page<Product> createPage(Integer pageIndex) {
		Page<Product> page = null;
		if (pageIndex != null) {
			page = new Page<Product>(pageIndex.intValue(),
					Constants.DEFAULT_PAGE_SIZE);
		} else {
			page = new Page<Product>();
		}
		return page;
	}

}
